package com.jichangxiu.framework.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.jichangxiu.common.annotation.Job;
import com.jichangxiu.common.annotation.Login;
import com.jichangxiu.common.annotation.Power;
import com.jichangxiu.common.annotation.Role;
import com.jichangxiu.framework.utils.AuthUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class AuthAspect {

    @Pointcut(" @annotation(com.jichangxiu.common.annotation.Login) || "
            + "@annotation(com.jichangxiu.common.annotation.Job) || "
            + "@annotation(com.jichangxiu.common.annotation.Power) || "
            + "@annotation(com.jichangxiu.common.annotation.Role)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 注解鉴权
        checkMethodAnnotation(((MethodSignature) joinPoint.getSignature()).getMethod());
        // 执行原有逻辑
        return joinPoint.proceed();
    }

    public void checkMethodAnnotation(Method method) {
        // 校验 @Login 注解
        Login login = method.getAnnotation(Login.class);
        if (ObjectUtil.isNotNull(login)) {
            AuthUtils.checkLogin();
        }
        // 校验 @Post 注解
        Job job = method.getAnnotation(Job.class);
        if (ObjectUtil.isNotNull(job)) {
            AuthUtils.checkJob(job);
        }
        // 校验 @Role 注解
        Role role = method.getAnnotation(Role.class);
        if (ObjectUtil.isNotNull(role)) {
            AuthUtils.checkRole(role);
        }
        // 校验 @Power 注解
        Power power = method.getAnnotation(Power.class);
        if (ObjectUtil.isNotNull(power)) {
            AuthUtils.checkPower(power);
        }
    }

}
